package net.dl.ss.dao.jdbc;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import net.dl.ss.dao.EventDao;
import net.dl.ss.domain.Event;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
public class EventDaoJDBC extends SimpleJdbcDaoSupport implements EventDao {
	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	
	@SuppressWarnings("unchecked")
    public <T> List<T> list(Class<T> event) {
		logger.info("Getting events!");
		List events = getSimpleJdbcTemplate().query(
				"select PK_EVENT_ID, TITLE, DATE, TYPE, RANK, PLACE, ORGANIZER," +
				"MASTER_OF_CEREMONY, CHAIRMAN, MUSIC, SCRUTINEER, SUPPORT from DLSS_EVENTS",
				new EventMapper());
		return events;
	}
	
	@SuppressWarnings("unchecked")
    public <T> T saveEntity(T entity) {
		Event event = (Event) entity;
		logger.info("Saving event: " + event.getTitle());
		int count = getSimpleJdbcTemplate().update(
				"update DLSS_EVENTS set title = :title where PK_EVENT_ID = :id",
				new MapSqlParameterSource().addValue("title", event.getTitle())
		.addValue("id", event.getId()));
		logger.info("Rows affected: " + count);
		return (T) event;
	}
	
	public void deleteEntity(Object entity) {
		// TODO Auto-generated method stub
		
	}

	public void deleteEntityById(Long id) {
		// TODO Auto-generated method stub
		
	}

	public <T> T get(Class<T> c, Serializable id) {
		// TODO Auto-generated method stub
		return null;
	}

	public <T> T load(T object, Serializable id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void updateEntity(Object entity) {
		// TODO Auto-generated method stub
		
	}
	
	private static class EventMapper implements ParameterizedRowMapper<Event> {
		public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
			Event event = new Event();
			event.setId(rs.getLong("PK_EVENT_ID"));
			event.setTitle(rs.getString("TITLE"));
			//TODO:
			return event;
		}
	}
	
}
